package com.fansl.koala.quickdev.common.utils;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author fansl
 * @Description: TODO
 * @date 2020/4/7 14:09
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(2, 2,
                60, TimeUnit.SECONDS, new ArrayBlockingQueue(20), Executors.defaultThreadFactory());
        final  Semaphore semaphore = new Semaphore(5);
        for (int i=0; i<20; i++){
            final  int no = i;
            Runnable runnable = () -> {
                try {
                    semaphore.acquire();
                    System.out.println("Accessing:"+no);
                    Thread.sleep(new Random().nextInt(1000));
                    semaphore.release();
                    System.out.println("*"+ semaphore.availablePermits());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
            executorService.execute(runnable);
        }
        executorService.shutdown();
    }
}
